package net.sansi.v3correctserver.constenum;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.sansi.v3correctserver.exception.ServiceException;
import net.sansi.v3correctserver.service.project.ProjectService;
import net.sansi.v3correctserver.service.space.ProjectSpace;
import net.sansi.v3correctserver.task.V3TaskManager;

import java.util.Map;

/**
 * Created by Fang
 * create time : 2024/11/4
 * IDE : IntelliJ IDEA
 * <p>
 * 访问助手
 */
@Slf4j
public class AppHelper {

    @Getter
    private static final V3TaskManager taskManager = new V3TaskManager();

    /**
     * 获取本次请求针对的项目空间
     * 1. 从 http header 中读取 projectid;
     * 2. 通过 projectid 获取项目空间
     *
     * @return 项目空间
     */
    public static ProjectSpace projectSpace() {
        return projectSpace(true);
    }

    /**
     * 获取本次请求针对的项目空间
     *
     * @param throwErr 是否抛出异常
     * @return 项目空间
     */
    public static ProjectSpace projectSpace(boolean throwErr) {
        Map<String, String> headers = ThreadLocalValues.instance.requestHeaders.get();
        String projectid = headers.get("projectid");
        if (projectid == null) {
            if (throwErr) throw new ServiceException("header 中缺少 projectid");
            else return null;
        }
        ProjectSpace space = ProjectService.getInstance().getProjectSpaceById(projectid);
        if (space == null) throw new ServiceException("项目不存在 [id] {}", projectid);
        return space;
    }


    /**
     * 获取请求头信息
     * 1. 在V3Task子线程中保持
     *
     * @param key 请求头信息
     * @return 请求头信息
     */
    public static String getHeader(String key) {
        return ThreadLocalValues.instance.requestHeaders.get().get(key);
    }
}
